import React, { Fragment } from 'react';
import PropTypes from 'prop-types';
import { authKey, unAuthUrl } from '../utils/Constant'
import {Card, Icon, Layout, message, Input} from 'antd';
import DocumentTitle from 'react-document-title';
import { connect } from 'dva';

import { Route, routerRedux, Redirect, Switch } from 'dva/router';
import { ContainerQuery } from 'react-container-query';
import classNames from 'classnames';
import pathToRegexp from 'path-to-regexp';
import { enquireScreen, unenquireScreen } from 'enquire-js';
import GlobalHeader from '../components/GlobalHeader';
import GlobalFooter from '../components/GlobalFooter';
import SiderMenu from '../components/SiderMenu';
import NotFound from '../routes/Exception/404';
import { getRoutes } from '../utils/utils';

import { getMenuData } from '../common/menu';
import logo from '../assets/logo.svg';
import EditForm from "../components/AutoForm/EditForm";

const { Content, Header, Footer } = Layout;

/**
 * 根据菜单取得重定向地址.
 */
const redirectData = [];
const getRedirect = item => {
  if (item && item.children) {
    if (item.children[0] && item.children[0].path) {
      redirectData.push({
        from: `${item.path}`,
        to: `${item.children[0].path}`,
      });
      item.children.forEach(children => {
        getRedirect(children);
      });
    }
  }
};

/**
 * 获取面包屑映射
 * @param {Object} menuData 菜单配置
 * @param {Object} routerData 路由配置
 */
const getBreadcrumbNameMap = (menuData, routerData) => {
  const result = {};
  const childResult = {};
  for (const i of menuData) {
    if (!routerData[i.path]) {
      result[i.path] = i;
    }
    if (i.children) {
      Object.assign(childResult, getBreadcrumbNameMap(i.children, routerData));
    }
  }
  return Object.assign({}, routerData, result, childResult);
};

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

let isMobile;
enquireScreen(b => {
  isMobile = b;
});

@connect(({ user, global = {}, loading }) => ({
  currentUser: user.currentUser,
  collapsed: global.collapsed,
  passwordLoading: loading.effects['tmsUser/updatePassword'],
  fetchingNotices: loading.effects['global/fetchNotices'],
  defaultRedirect: global.defaultRedirect,
  notices: global.notices,
  menuData: global.menuData,
}))
export default class BasicLayout extends React.PureComponent {
  static childContextTypes = {
    location: PropTypes.object,
    breadcrumbNameMap: PropTypes.object,
  };

  state = {
    isMobile,
    passwordModal: false,
    passwordRows: [
      {
        cols: [
          {
            label: '旧密码',
            name: 'password1',
            md: 24,
            rules: [{ required: true, message: ' ' }],
            component: <Input.Password />,
          },
        ],
      },

      {
        cols: [
          {
            label: '新密码',
            name: 'newPassword',
            md: 24,
            rules: [{ required: true, message: ' ' }],
            component: <Input.Password />,
          },
        ],
      },
      {
        cols: [
          {
            label: '确认密码',
            name: 'password2',
            md: 24,
            rules: [{ required: true, message: ' ' }],
            component: <Input.Password />,
          },
        ],
      },
    ],
    passwordForm: {},
  };

  getChildContext() {
    const { location, routerData, menuData } = this.props;
    return {
      location,
      breadcrumbNameMap: getBreadcrumbNameMap(getMenuData(menuData), routerData),
    };
  }

  componentDidMount() {
    const { menuData } = this.props;
    getMenuData(menuData).forEach(getRedirect);
    this.enquireHandler = enquireScreen(mobile => {
      this.setState({
        isMobile: mobile,
      });
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });
    dispatch({
      type: 'global/fetchDefaultRedirect',
    });
  }

  componentWillUnmount() {
    unenquireScreen(this.enquireHandler);
  }

  getPageTitle() {
    const { routerData, location } = this.props;
    const { pathname } = location;
    let title = '鑫连鑫';
    let currRouterData = null;
    // match params path
    Object.keys(routerData).forEach(key => {
      if (pathToRegexp(key).test(pathname)) {
        currRouterData = routerData[key];
      }
    });
    if (currRouterData && currRouterData.name) {
      title = `${currRouterData.name} - 鑫连鑫`;
    }
    return title;
  }

  handleMenuCollapse = collapsed => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };

  handleNoticeClear = type => {
    message.success(`清空了${type}`);
    const { dispatch } = this.props;
    dispatch({
      type: 'global/clearNotices',
      payload: type,
    });
  };

  handleMenuClick = ({ key }) => {
    const { dispatch } = this.props;
    if (key === 'triggerError') {
      dispatch(routerRedux.push('/exception/trigger'));
      return;
    }
    if (key === 'password') {
      this.setState({
        passwordModal: true,
      });
    }
    if (key === 'logout') {
      sessionStorage.setItem(authKey, "logout");
      window.location = unAuthUrl
    }
  };

  handlePasswordChange = fields => {
    const {passwordForm} = this.state
    const newForm = {
      ...passwordForm,
      ...fields
    }
    this.setState({
      passwordForm: newForm
    });
  };

  handlePasswordVisible = () => {
    this.setState({
      passwordModal: false,
    });
  };

  handlePasswordSub = () => {
    const { dispatch } = this.props
    const { passwordForm } = this.state;
    if(passwordForm['newPassword'].value !== passwordForm['password2'].value){
      return message.error("密码不一致！")
    }
    dispatch({
      type: 'tmsUser/updatePassword',
      payload: {userName: passwordForm['password1'].value, password: passwordForm['newPassword'].value}
    }).then(()=>{
      this.setState({
        passwordModal: false,
        passwordForm: {}
      })
    })
  }

  handleNoticeVisibleChange = visible => {
    const { dispatch } = this.props;
    if (visible) {
      dispatch({
        type: 'global/fetchNotices',
      });
    }
  };

  render() {
    const {
      currentUser,
      collapsed,
      fetchingNotices,
      notices,
      routerData,
      match,
      location,
      menuData,
      defaultRedirect,
      passwordLoading
    } = this.props;
    const { isMobile: mb } = this.state;

    const layout = (
      <Layout>
        <EditForm
          title="修改密码"
          rows={this.state.passwordRows}
          fieldValue={this.state.passwordForm}
          onFieldsChange={this.handlePasswordChange}
          onCancel={this.handlePasswordVisible}
          onOk={this.handlePasswordSub}
          confirmLoading={passwordLoading}
          visible={this.state.passwordModal}
        />
        <SiderMenu
          logo={logo}
          menuData={getMenuData(menuData)}
          collapsed={collapsed}
          location={location}
          isMobile={mb}
          onCollapse={this.handleMenuCollapse}
        />
        <Layout>
          <Header style={{ padding: 0 }}>
            <GlobalHeader
              logo={logo}
              currentUser={currentUser}
              fetchingNotices={fetchingNotices}
              notices={notices}
              collapsed={collapsed}
              isMobile={mb}
              onNoticeClear={this.handleNoticeClear}
              onCollapse={this.handleMenuCollapse}
              onMenuClick={this.handleMenuClick}
              onNoticeVisibleChange={this.handleNoticeVisibleChange}
            />
          </Header>
          <Content style={{ margin: '24px 24px 0', height: '100%' }}>
            <Switch>
              {getRoutes(match.path, routerData).map(item => (
                <Route key={item.key} path={item.path} component={item.component} />
              ))}
              <Redirect exact from="/" to={defaultRedirect} />
              <Route render={NotFound} />
            </Switch>
          </Content>
          <Footer style={{ padding: 0 }}>
            <GlobalFooter
              copyright={
                <Fragment>
                  Copyright <Icon type="copyright" /> 2020 快远科技技术部出品
                </Fragment>
              }
            />
          </Footer>
        </Layout>
      </Layout>
    );

    return (
      <DocumentTitle title={this.getPageTitle()}>
        <ContainerQuery query={query}>
          {params => <div className={classNames(params)}>{layout}</div>}
        </ContainerQuery>
      </DocumentTitle>
    );
  }
}
